<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        width: 400px;
        height: 500px;
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div id="box">
        <p v-for="(item, index) in contextList" :key="index">
          {{item.name}}说：{{ item.value }}
        </p>
      </div>
      <input type="text" v-model="textValue" />
      <button @click="send">发送</button>
    </div>

    <script src="./vue3.js"></script>
    <script>
      const name = prompt("请输入用户名");
      const id = new Date().getTime();
      let ws;

      const { createApp } = Vue;

      createApp({
        data() {
          return {
            textValue: "",
            contextList: [],
          };
        },
        // 页面加载完成了
        mounted() {
          ws = new WebSocket("ws://10.31.167.219:8080");

          // 连接成功的回调函数
          ws.onopen = function (evt) {
            console.log("Connection open ...");
            // send前端发给后端
            // ws.send("Hello WebSockets!");
          };

          // 接收到信息的回调函数
          ws.onmessage = (evt) => {
            // console.log("Received Message: " + evt.data);
            // 关闭长连接
            // ws.close();
            // box.innerHTML += `<p>${evt.data}</p>`;

            // const { name, value, key } = JSON.parse(evt.data);
            // 拿到的key是和当前页面的id相同的，就是本人
            // if (key === id) {
            //   box.innerHTML += `<p style="text-align: right">${name}说：${value}</p>`;
            // } else {
            //   box.innerHTML += `<p>${name}说：${value}</p>`;
            // }
            const obj = JSON.parse(evt.data);
            this.contextList.push(obj);
          };

          // 成功关闭的回调函数
          ws.onclose = function (evt) {
            console.log("Connection closed.");
          };
        },
        methods: {
          send() {
            ws.send(
              JSON.stringify({
                name: name,
                value: this.textValue,
                key: id,
              })
            );
            this.textValue = "";
          },
        },
      }).mount("#app");
    </script>
  </body>
</html>
